package com.share.factory.strategy;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.common.enums.HttpStatusEnum;
import com.share.common.enums.UserStatusEnum;
import com.share.exception.BaseException;
import com.share.properties.WeChatProperties;
import com.share.service.ISysUserService;
import com.share.service.OAuthService;
import com.share.service.WebSocketService;
import com.share.user.admin.pojos.SysUser;
import com.share.user.admin.vo.LoginVo;
import com.share.user.weChat.dtos.TokenInfo;
import com.share.user.weChat.dtos.WxUserInfo;
import com.share.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.UUID;

/**
 * 微信登录
 */
@Slf4j
@Service
public class WeChatAuthStrategy extends AbstractAuthStategy {

    private final WeChatProperties weChatProperties;
    private final WebSocketService webSocketService;
    private final TokenUtils tokenUtils;
    private final OAuthService oAuthService;
    private final ISysUserService sysUserService;

    @Autowired
    public WeChatAuthStrategy(WeChatProperties weChatProperties, WebSocketService webSocketService, TokenUtils tokenUtils, OAuthService oAuthService, ISysUserService sysUserService) {
        this.weChatProperties = weChatProperties;
        this.webSocketService = webSocketService;
        this.tokenUtils = tokenUtils;
        this.oAuthService = oAuthService;
        this.sysUserService = sysUserService;
    }

    @Override
    public void thirdPartyLogin(String code){
        log.info("微信登录回调");
        //获取access_token
        TokenInfo tokenInfo =
                oAuthService.getWxTokenInfo(code, weChatProperties.getAppId(),
                        weChatProperties.getAppSecret());
        //获取用户信息
        WxUserInfo wxUserInfo = oAuthService.getWxUserInfo(tokenInfo);
        log.info("获取微信账户信息:{}", wxUserInfo);
        if(wxUserInfo == null){
            throw new BaseException(HttpStatusEnum.FORBIDDEN,"登录失败", Instant.now());
        }
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getOpenId, wxUserInfo.getOpenid());
        SysUser sysUser = sysUserService.getOne(lambdaQueryWrapper);
        if(sysUser == null){
            //创建账号并登录
            sysUser = new SysUser();
            sysUser.setOpenId(wxUserInfo.getOpenid());
            sysUser.setNickname(wxUserInfo.getNickname());
            sysUser.setUsername("wx-"+ UUID.randomUUID().toString().substring(7));
            sysUser.setAvatar(wxUserInfo.getHeadimgurl());
            sysUser.setStatus(UserStatusEnum.ACTIVE);
            sysUserService.save(sysUser);
        }
        LoginVo loginVo = tokenUtils.LoginInformation(sysUser);
        // 4. 仅发送给该用户（而不是广播）
        webSocketService.sendMessageToClients(JSON.toJSONString(loginVo));
    }

}
